package com.edu.ahm.thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/*
*  练习Thread 多线程同步下载图片
*
* */
public class MyThread2 extends Thread {

    private String url; //网络图片地址
    private String name; // 保存的图片名

    public MyThread2(String url,String name){
        this.url = url;
        this.name = name;
    }

    @Override
    public void run() {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downloader(url,name);
        System.out.println("下载了文件名为："+ name);
    }

    //    public void run(){

//    }

    public static void main(String[] args) {
        MyThread2 thread1 = new MyThread2("https://pic1.58cdn.com.cn/p1/big/n_v229efc92f51804ca0bde8a7899e718a72.jpg","1.jpg");
        MyThread2 thread2 = new MyThread2("https://pic1.58cdn.com.cn/p1/big/n_v229efc92f51804ca0bde8a7899e718a72.jpg","2.jpg");
        MyThread2 thread3 = new MyThread2("https://pic1.58cdn.com.cn/p1/big/n_v229efc92f51804ca0bde8a7899e718a72.jpg","3.jpg");
        // 线程 先后不一定 同时的 看cpu心情喽 每次结果都不一定相同
        thread1.start();
        thread2.start();
        thread3.start();
    }

}

// 下载器
class WebDownLoader{
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("downloader有异常");
        }
    }

}
